package org.meetunexpectedly.limit;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.meetunexpectedly.constant.RedisConstant;
import org.meetunexpectedly.exception.LimiterException;
import org.meetunexpectedly.holder.UserHolder;
import org.meetunexpectedly.util.RedisCacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.util.ObjectUtils;


/**
 * @Description: limitCount 切面类
 * @Author: pupil
 * @Date: 2024/08/18 下午 4:10
 */
@Async // 异步
public class LimiterAop {

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    /**
     * 拦截
     * @param joinPoint
     * @param limit
     * @return
     */
    @Before("@annotation(limit)")
    public Object restriction(ProceedingJoinPoint joinPoint,Limit limit) throws Throwable {
        Long userId = UserHolder.get(); // 当前用户id
        int limitCount = limit.limitCount(); // 限制次数
        String msg = limit.msg(); // 限制消息
        long time = limit.time(); // 限制时间

        String key = RedisConstant.VIDEO_LIMIT + userId;
        Object o = redisCacheUtil.get(key);
        if (ObjectUtils.isEmpty(o)){
            redisCacheUtil.set(key,1,time);
        }else {
            if (Integer.parseInt(o.toString()) > limitCount){
                throw new LimiterException(msg);
            }
            redisCacheUtil.increment(key,1);
        }
        Object proceed = joinPoint.proceed();
        return proceed;
    }
}
